import jwt
from datetime import datetime, timedelta
from django.conf import settings
from rest_framework.exceptions import AuthenticationFailed


class JwtUtils:
    """JWT认证工具类"""

    @staticmethod
    def generate_token(user_id: int) -> str:
        """
        生成JWT token

        Args:
            user_id: 用户ID
            expires_in: 过期时间（秒）

        Returns:
            JWT token字符串
        """
        # 获取SECRET_KEY
        secret_key = settings.SECRET_KEY

        # 计算过期时间
        exp = datetime.utcnow() + timedelta(days=7)

        # 构建payload
        payload = {
            'user_id': user_id,
            'exp': exp,
            'iat': datetime.utcnow()
        }


        # 生成token
        token = jwt.encode(
            payload,
            secret_key,
            algorithm='HS256'
        )

        return token

    @staticmethod
    def decode_token(token: str) -> dict:
        """
        解析JWT token

        Args:
            token: JWT token字符串

        Returns:
            解析后的payload

        Raises:
            AuthenticationFailed: token无效或过期
        """
        # 获取SECRET_KEY
        secret_key = settings.SECRET_KEY

        try:
            # 解析token
            payload = jwt.decode(
                token,
                secret_key,
                algorithms=['HS256']
            )
            return payload
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('Token已过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('无效的Token')

    @staticmethod
    def encode(pyload: dict) -> str:
        """
        编码pyload为JWT token

        :param payload: 要编码的数据字典
        :return: JWT token字符串
        """
        # 获取SECRET_KEY
        secret_key = settings.SECRET_KEY
        return jwt.encode(pyload, secret_key, algorithm='HS256')

    @staticmethod
    def get_user_id_from_token(token: str) -> int:
        """
        从token中获取用户ID

        Args:
            token: JWT token字符串

        Returns:
            用户ID

        Raises:
            AuthenticationFailed: token无效或过期
        """
        payload = JwtUtils.decode_token(token)
        return payload.get('user_id')


jwtTool = JwtUtils()
